﻿using DevExpress.ExpressApp;
using DevExpress.ExpressApp.DC;
using System.Xml.Linq;

namespace EasyXaf.EntityDesigner.Editors.DetailViewEditors.Models;

/// <summary>
/// 组件
/// </summary>
[DomainComponent]
public abstract class Component : NonPersistentLiteObject
{
    private double? _size;
    private string _minSize;
    private string _maxSize;
    private string _sizeConstraintsType;

    /// <summary>
    /// 大小
    /// </summary>
    [XafDisplayName("大小")]
    public double? Size
    {
        get => _size;
        set => SetPropertyValue(ref _size, value);
    }

    /// <summary>
    /// 最小大小
    /// </summary>
    [XafDisplayName("最小大小")]
    public string MinSize
    {
        get => _minSize;
        set => SetPropertyValue(ref _minSize, value);
    }

    /// <summary>
    /// 最大大小
    /// </summary>
    [XafDisplayName("最大大小")]
    public string MaxSize
    {
        get => _maxSize;
        set => SetPropertyValue(ref _maxSize, value);
    }

    /// <summary>
    /// 大小约束类型
    /// </summary>
    [XafDisplayName("大小约束类型")]
    public string SizeConstraintsType
    {
        get => _sizeConstraintsType;
        set => SetPropertyValue(ref _sizeConstraintsType, value);
    }

    public Component Parent { get; set; }

    public LayoutDesigner LayoutDesigner { get; }

    public Component(Component parent, LayoutDesigner layoutDesigner)
    {
        Parent = parent;
        LayoutDesigner = layoutDesigner;
    }

    protected static void SetXmlAttributeValue<T>(XElement element, string name, T value)
    {
        element.SetAttributeValue(name, value);
    }

    protected static T GetXmlAttributeValue<T>(XElement element, string name, T defaultValue = default)
    {
        if (element.Attribute(name) is XAttribute attribute)
        {
            return (T)(dynamic)attribute;
        }
        return defaultValue;
    }

    public virtual void WriteToXml(XElement element)
    {
        if (Size.HasValue)
        {
            SetXmlAttributeValue(element, "size", Size);
        }

        if (!string.IsNullOrWhiteSpace(MinSize))
        {
            SetXmlAttributeValue(element, "min-size", MinSize);
        }

        if (!string.IsNullOrWhiteSpace(MaxSize))
        {
            SetXmlAttributeValue(element, "max-size", MaxSize);
        }

        if (!string.IsNullOrWhiteSpace(SizeConstraintsType))
        {
            SetXmlAttributeValue(element, "size-constraints-type", SizeConstraintsType);
        }
    }

    public virtual void ReadFromXml(XElement element)
    {
        Size = GetXmlAttributeValue<double?>(element, "size");
        MinSize = GetXmlAttributeValue<string>(element, "min-size");
        MaxSize = GetXmlAttributeValue<string>(element, "max-size");
        SizeConstraintsType = GetXmlAttributeValue<string>(element, "size-constraints-type");
    }

    public abstract XElement CreateXElement();
}
